<template>
  <div>
    <div name="backgourd" style="display: flex;flex-direction: column; justify-items: center;height: 100vh">
      <!--    未发布或定时发布的日志展示、提交提醒-->
      <div name="noteInfoShow" style="display: flex;align-items: center;justify-items: left;height: 30%">
        <div style="width: 70%;height: 100%;display: flex; flex-direction:column;justify-items: left;margin: 12px;
background-color: white; border-radius: 12px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
">
          <span
              style="font-size: 20px;font-family: 'PingFang SC';font-weight: bolder;margin: 6px;margin-left: 12px;height: 42px;
display: flex;align-items: center;
">
            <i class="el-icon-tickets"></i>
            <div style="width: 10%">
               未发布日志
            </div>

            <!--            下面是搜索条件-->
             <div
                 style="display: flex;align-items: center;justify-content: center;width: 90%; height: 100%;margin-left: 4px">
          <div style="width: 30%; display: flex;align-items: center;justify-content: center">
            <span style="font-weight: bolder;font-family: 'PingFang SC';font-size: 12px;margin: 6px">日志名称:</span>
            <!--            <el-select v-model="projectSelectValue" placeholder="请选择所属项目">-->
              <el-input v-model="noteNameSelectValue" placeholder="请输入日志名称" size="small" style="width: auto"></el-input>
          </div>

          <div style="width: 30%; display: flex;align-items: center;justify-content: center">
            <span style="font-weight: bolder;font-family: 'PingFang SC';font-size: 12px;margin: 6px">日志类型:</span>
            <el-select v-model="noteTypeSelectValue" placeholder="请选择日志类型">
              <el-option
                  v-for="item in noteTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              >
              </el-option>
            </el-select>
          </div>

          <div style="width: 30%; display: flex;align-items: center;justify-content: center">
            <span style="font-weight: bolder;font-family: 'PingFang SC';font-size: 12px;margin: 6px">发布日期:</span>
             <el-date-picker
                 v-model="publishTimeSelectValue"
                 type="date"
                 placeholder="选择日期">
            </el-date-picker>

          </div>

          <div style="width: 10%; display: flex;align-items: center;justify-content: center">
            <el-button icon="el-icon-search" circle @click="getMyUnSubmitNotesConditional"></el-button>
            <el-button icon="el-icon-refresh" circle @click="reSetMyUnSubmitNoteSelectCondition"></el-button>
          </div>
        </div>
          </span>
          <el-table
              :data="unSubmitNoteList"
              height="290px"
              style="width: 100%;height: 100px">
            <el-table-column
                prop="noteId"
                label="日志Id"
            >
            </el-table-column>
            <el-table-column
                prop="noteName"
                label="日志名称"
            >
            </el-table-column>
            <el-table-column
                prop="noteType"
                label="类型">

              <template slot-scope="scope">
                <el-tag
                    disable-transitions
                    effect="Plain"
                >{{ switchNoteType(scope.row.noteType).noteTypeName }}
                </el-tag>
              </template>

            </el-table-column>

            <el-table-column
                prop="publishTime"
                label="发布时间">
              <template slot-scope="scope">
                {{ timeFormatConversion(scope.row) }}
              </template>
            </el-table-column>

            <el-table-column
                prop="noteStatus"
                label="状态">
              <template slot-scope="scope">
                <el-tag
                    :type="switchNoteStatus(scope.row.noteStatus).tagStyle"
                    disable-transitions
                    effect="dark"
                >{{ switchNoteStatus(scope.row.noteStatus).noteStatusName }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                    size="mini"
                    @click="editNote(scope.row)"
                >编辑
                </el-button>

              </template>
            </el-table-column>
          </el-table>
        </div>
        <div style="width: 30%;height: 100%;display: flex; flex-direction:column;justify-items: center;align-items: center;margin-bottom: 12px;
margin-right: 12px; margin-top: 12px;
background-color: white; border-radius: 12px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
">
         <span
             style="font-size: 20px;font-family: 'PingFang SC';font-weight: bolder;margin: 6px;margin-left: 12px">
           <i class="el-icon-bell"></i>
           提交提醒
           <el-button @click="readAllMsgs" type="success" icon="el-icon-check" plain size="mini">已读</el-button>
         </span>
          <el-table
              :data="reminderList"
              height="290px"
              style="width: 100%;height: 100px"
              @selection-change="handleSelectionChange"
          >

            <!--            选中框-->
            <el-table-column
                type="selection"
                width="55">
            </el-table-column>
            <!--下标-->
            <el-table-column
                type="index"
                width="auto">
            </el-table-column>

            <el-table-column
                prop="msgContent"
                label="消息内容"
                width="200px"
            >
            </el-table-column>
            <el-table-column
                prop="msgStatus"
                label="消息状态"
            >
              <template slot-scope="scope">
                <el-tag
                    :type="switchMsgStatus(scope.row.msgStatus).tagStyle"
                    disable-transitions
                    effect="dark"
                >{{ switchMsgStatus(scope.row.msgStatus).msgStatusName }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                    size="mini"
                    @click="readMsg(scope.row.tableId)"
                >已读
                </el-button>
              </template>
            </el-table-column>
          </el-table>

        </div>
      </div>

      <!--      日志内容区域-->
      <div name="noteContent" style="display: flex; flex-direction:column;align-items: center;justify-items: center;height: 70%;margin: 12px;
background-color: white; border-radius: 12px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
">
        <!--        日志类型、日志名称、日志发布日期-->
        <div style="display: flex;align-items: center;justify-content: center;width: 100%; height: 8%">
          <!--          <div style="width: 30%; display: flex;align-items: center;justify-content: center">
                      <span style="font-weight: bolder;font-family: 'PingFang SC';font-size: 12px;margin: 6px">所属项目:</span>
                      <el-select v-model="projectSelectValue" placeholder="请选择所属项目">
                        <el-option
                            v-for="item in projectOptions"
                            :key="item.projectId"
                            :label="item.projectName"
                            :value="item.projectId">
                        </el-option>
                      </el-select>

                    </div>

                    <div style="width: 30%; display: flex;align-items: center;justify-content: center">
                      <span style="font-weight: bolder;font-family: 'PingFang SC';font-size: 12px;margin: 6px">任务类型:</span>
                      <el-select v-model="taskTypeSelectValue" placeholder="请选择任务类型">
                        <el-option
                            v-for="item in taskTypeOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                      </el-select>
                    </div>

                    <div style="width: 30%; display: flex;align-items: center;justify-content: center">
                      <span style="font-weight: bolder;font-family: 'PingFang SC';font-size: 12px;margin: 6px">发布日期:</span>
                      <el-select v-model="taskPrioritySelectValue" placeholder="请选择任务级别">
                        <el-option
                            v-for="item in taskPriorityOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                      </el-select>

                    </div>-->

          <div style="width: 30%; display: flex;align-items: center;justify-content: center">
            <span style="font-weight: bolder;font-family: 'PingFang SC';font-size: 12px;margin: 6px">日志类型:</span>
            <el-select v-model="addNoteTypeSelectValue" placeholder="请选择任务类型">
              <el-option
                  v-for="item in noteTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              >
              </el-option>
            </el-select>
          </div>

          <div style="width: 30%; display: flex;align-items: center;justify-content: center">
            <span style="font-weight: bolder;font-family: 'PingFang SC';font-size: 12px;margin: 6px">日志名称:</span>
            <!--            <el-select v-model="projectSelectValue" placeholder="请选择所属项目">-->
            <el-input v-model="addNoteNameValue" placeholder="请输入日志名称" size="small" style="width: 80%"></el-input>
          </div>


          <div style="width: 30%; display: flex;align-items: center;justify-content: center">
            <span style="font-weight: bolder;font-family: 'PingFang SC';font-size: 12px;margin: 6px">发布日期:</span>
            <el-date-picker
                v-model="addNotePublishTimeDateSelectValue"
                type="date"
                placeholder="选择日期" style="width: 37%">
            </el-date-picker>
            <span style="margin: 6px">-</span>
            <el-time-picker placeholder="选择时间" v-model="addNotePublishTimeSelectValue"
                            style="width: 30%"></el-time-picker>
          </div>

          <el-button icon="el-icon-refresh" circle @click="reSetConditionOfPublishOrSaveNote"></el-button>

          <div style="width: 30%; display: flex;align-items: center;justify-content: center">
            <el-button type="primary" style="width: 37%;margin: 12px" @click="publishNote">发布
            </el-button>
            <el-button style="width: 37%;margin: 12px" @click="saveNote">保存
            </el-button>
          </div>
        </div>

        <div style="width: 100%;height: 92%">
          <!--        md文档编辑区域-->
          <v-md-editor v-model="text" height="100%"
                       :disabled-menus="[]"
                       @upload-image="handleUploadImage"
                       left-toolbar="undo redo clear | h bold italic strikethrough quote | ul ol table hr | link image code"
          ></v-md-editor>
        </div>

      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "MyNotes",
  mounted() {
    this.$request.get("/note/getMyUnSubmitNote", {
      params: {
        publishUserid: this.loginUser.uid
      }
    }).then(res => {
      if (res.successFlag) {
        this.unSubmitNoteList = res.data
      } else {
        this.$message.error(res.errorMsg)
      }
    })

    this.$request.get("/remind/getMyRemind", {
      params: {
        userId: this.loginUser.uid
      }
    }).then(res => {
      if (res.successFlag) {
        this.reminderList = res.data
      } else {
        this.$message.error(res.errorMsg)
      }
    })

    //判断是否有从“日志管理传来的editNote”,有则显示
    if (this.editNoteEntity!== undefined && this.editNoteEntity !== null){
      this.editNote(this.editNoteEntity);
      localStorage.removeItem("editNote")
    }

  },
  data() {
    return {
      editNoteEntity:JSON.parse(localStorage.getItem("editNote")),

      //日志绑定实体
      noteEntity: {
        noteId: null,
        noteName: '',
        noteType: '',
        publishUserId: '',
        noteImages: null,
        noteContent: '',
        noteStatus: 3,
        createTime: '',
        updateTime: '',
        publishTimeOfDate: '',
        publishTimeOfTime: ''
      },
      unSubmitNoteList: [],//未发布的日志数据绑定
      reminderList: [], //提交提醒数据绑定
      loginUser: JSON.parse(localStorage.getItem("loginUser")), //当前登录用户

      noteTypeSelectValue: '',  //日志类型选中
      noteTypeOptions: [ //日志类型选项
        {
          value: 0,
          label: '日报'
        },
        {
          value: 1,
          label: '周报'
        }, {
          value: 2,
          label: '月度总结'
        }
      ],

      publishTimeSelectValue: '',//发布时间选中绑定
      noteNameSelectValue: '',//日志名字查询绑定

      addNoteNameValue: '',//新增日志的日志名称绑定
      addNoteTypeSelectValue: '',//新增日志的日志类型选中
      addNotePublishTimeSelectValue: '',//新增日志的发布时间
      addNotePublishTimeDateSelectValue: '',//新增日志的发布日期

      multipleSelection: [], //提交提醒选中

      text: '',//文本内容设置了默认模板


    }
  },
  methods: {
    switchNoteType(noteType) {
      let reslut = {
        noteTypeName: ''
      }
      if (noteType === 0) {
        reslut.noteTypeName = '日报'
        return reslut
      } else if (noteType === 1) {
        reslut.noteTypeName = '周报'
        return reslut
      } else if (noteType === 2) {
        reslut.noteTypeName = '月度总结'
        return reslut
      }
      return reslut
    },

    switchNoteStatus(noteStatus) {
      let reslut = {
        tagStyle: '',
        noteStatusName: ''
      }
      if (noteStatus === 0) {
        reslut.tagStyle = 'warning'
        reslut.noteStatusName = '保存未发布'
        return reslut
      } else if (noteStatus === 1) {
        reslut.tagStyle = 'success'
        reslut.noteStatusName = '已发布'
        return reslut
      } else if (noteStatus === 2) {
        reslut.tagStyle = ''
        reslut.noteStatusName = '定时发布'
        return reslut
      }
      return reslut
    },

    switchMsgStatus(msgStatus) {
      let reslut = {
        tagStyle: '',
        msgStatusName: ''
      }
      if (msgStatus === 0) {
        reslut.tagStyle = 'warning'
        reslut.msgStatusName = '未读'
        return reslut
      } else if (msgStatus === 1) {
        reslut.tagStyle = 'success'
        reslut.msgStatusName = '已读'
        return reslut
      }
      return reslut
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    readMsg(tableId) {
      this.$request.put("/remind/readRemind" + "?tableId=" + tableId).then(
          async res => {
            if (res.successFlag) {
              await this.getMyRemindMsgs()
            } else {
              this.$message.error(res.errorMsg)
            }
          }
      )
    },

    readAllMsgs() {
      if (this.multipleSelection == []) {
        this.$message.error("请先选中！")
      } else {
        this.$request.put("/remind/readAllRemind", this.multipleSelection).then(
            async res => {
              if (res.successFlag) {
                await this.getMyRemindMsgs()
              } else {
                this.$message.error(res.errorMsg)
              }
            }
        )
      }
    },
    getMyRemindMsgs() {
      this.$request.get("/remind/getMyRemind", {
        params: {
          userId: this.loginUser.uid
        }
      }).then(res => {
        if (res.successFlag) {
          this.reminderList = res.data
        } else {
          this.$message.error(res.errorMsg)
        }
      })
    },

    getMyUnSubmitNotesConditional() {
      this.$request.get("/note/getNoteConditionalQueryByPage", {
        params: {
          publishUserid: this.loginUser.uid,
          currentPage: '',
          pageSize: '',
          noteStatusSelectValue: '',
          noteTypeSelectValue: this.noteTypeSelectValue,
          publishTime: this.publishTimeSelectValue,
          noteNameSelectValue: this.noteNameSelectValue,
          queryType: 2 //表示只进行条件查询，不分页
        }
      }).then(res => {
        if (res.successFlag) {
          this.unSubmitNoteList = res.data
        } else {
          this.$message.error(res.errorMsg)
        }
      })
    },
    reSetMyUnSubmitNoteSelectCondition() {
      this.noteTypeSelectValue = ''
      this.publishTimeSelectValue = ''
      this.noteNameSelectValue = ''
      this.getMyUnSubmitNote()
    },
    getMyUnSubmitNote() {
      this.$request.get("/note/getMyUnSubmitNote", {
        params: {
          publishUserid: this.loginUser.uid
        }
      }).then(res => {
        if (res.successFlag) {
          this.unSubmitNoteList = res.data
        } else {
          this.$message.error(res.errorMsg)
        }
      })
    },

    //发布日志
    publishNote() {
      this.noteEntity.noteName = this.addNoteNameValue
      this.noteEntity.noteType = this.addNoteTypeSelectValue
      this.noteEntity.publishUserId = this.loginUser.uid
      this.noteEntity.noteContent = this.text

      /* let chinaTime = this.convertToChinaTime(this.addNotePublishTimeDateSelectValue);*/

      this.noteEntity.publishTimeOfDate = this.addNotePublishTimeDateSelectValue
      this.noteEntity.publishTimeOfTime = this.addNotePublishTimeSelectValue
      this.$request.post("/note/publishNote", this.noteEntity).then(res => {
        if (res.successFlag) {
          //刷新页面
          this.$message.success(res.data)
          location.reload();
        } else {
          this.$message.error(res.errorMsg)
        }
      })
    },

    /*convertToChinaTime(selectedTime) {
      // 假设 selectedTime 是 HH:mm 格式的字符串
      // 将其解析为 Date 对象并设置时区为 Asia/Shanghai（北京时间）
      const timeArray = selectedTime.split(":");
      const date = new Date();
      date.setHours(parseInt(timeArray[0], 10));
      date.setMinutes(parseInt(timeArray[1], 10));
      date.setSeconds(0);
      date.setMilliseconds(0);

      return date.toISOString(); // 返回 ISO 格式的字符串
    },*/

    //保存日志
    saveNote() {
      //设置日志状态为保存
      this.noteEntity.noteStatus = 0

      this.noteEntity.noteName = this.addNoteNameValue
      this.noteEntity.noteType = this.addNoteTypeSelectValue
      this.noteEntity.publishUserId = this.loginUser.uid
      this.noteEntity.noteContent = this.text

      /* let chinaTime = this.convertToChinaTime(this.addNotePublishTimeDateSelectValue);*/

      this.noteEntity.publishTimeOfDate = this.addNotePublishTimeDateSelectValue
      this.noteEntity.publishTimeOfTime = this.addNotePublishTimeSelectValue

      this.$request.post("/note/publishNote", this.noteEntity).then(res => {
        if (res.successFlag) {
          this.$message.success(res.data)
          location.reload();
        } else {
          this.$message.error(res.errorMsg)
        }
      })
    },

    //发布或保存日志的数据绑定重置
    reSetConditionOfPublishOrSaveNote() {
      this.addNoteNameValue = ''
      this.addNoteTypeSelectValue = ''
      this.addNotePublishTimeDateSelectValue = ''
      this.addNotePublishTimeSelectValue = ''
    },

    //日期转换
    timeFormatConversion(note) {
      let showDate = ''
      /*if (publishTime != null) {
        showDate = publishTime[0] + '年' + publishTime[1] + '月' + publishTime[2] + '日' + '-' + publishTime[3] + ':' + publishTime[4]
      } else {
        showDate = '暂无日期'
      }*/
      const [year, month, day, hours, minutes] = note.publishTime;
      // Format time as "YYYY年M月D日-HH：mm"
      const formattedTime = `${year}年${month}月${day}日-${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`;
      // Save the formatted time string to the data property
      showDate = formattedTime
      return showDate
    },


    //编辑保存但是未发布的日志
    editNote(note) {
      //先将数据绑定
      this.addNoteNameValue = note.noteName
      this.addNoteTypeSelectValue = note.noteType
      this.text = note.noteContent
      this.noteEntity.noteId = note.noteId
      //日期解析绑定
      const [year, month, day, hours, minutes, seconds] = note.publishTime;

      // Format date as yyyy-MM-dd
      const formattedDate = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;

      // Format time as HH:mm
      const formattedTime = `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`;

      // Combine date and time
      const combinedDateTime = `${formattedDate}T${formattedTime}`;

      // Save values to the data properties
      this.addNotePublishTimeSelectValue = combinedDateTime
      this.addNotePublishTimeDateSelectValue = combinedDateTime
    },

    //编写日志md文档，支持图片文件上传
    handleUploadImage(event, insertImage, files) {
      // 拿到 files 之后上传到文件服务器，然后向编辑框中插入对应的内容
      console.log(files);
      this.$request.post("/note/uploadImageToMinio", this.text).then(res => {
        console.log(res)
      })
      // 此处只做示例
      insertImage({
        url:
            '',
        desc: '',
        width: 'auto',
        height: 'auto',
      });
    },


    //日志类型选中时切换不同的日志模板
    /*noteTypeChange(noteTypeSelectValue){
      //根据选中值切换不同日志模板
      let  daily="# 日期： 20XX年XX月XX日 （日报）\n" +
          "姓名：XXX     职位：XXX\n" +
          "## 昨日工作总结\n" +
          "XXX\n" +
          "## 今日工作安排\n" +
          "XXX"
      let weekly="# 日期： 20XX年XX月XX日 （周报）\n" +
          "姓名：XXX     职位：XXX\n" +
          "## 本周工作汇总\n" +
          "XXX\n" +
          "## 未完成工作说明\n" +
          "XXX "
      let monthly ="# 日期： 20XX年XX月XX日 （月度总结）\n" +
          "姓名：XXX     职位：XXX\n" +
          "## 本月工作亮点\n" +
          "XXX\n" +
          "## 未完成的工作\n" +
          "XXX\n" +
          "## 自我评价\n" +
          "XXX"

      debugger
      if (noteTypeSelectValue===0){
        this.text=daily
      }else if (noteTypeSelectValue===1){
        this.text=weekly
      }else if (noteTypeSelectValue===2){
        this.text=monthly
      }else {
        this.text=''
      }
    },*/


  }
}
</script>

<style scoped>

</style>